<template>
    <!-- 添加观察目标元素 -->
    <div ref="target" class="observer-target" :class="{ 'no-more': !hasMore }">
        <div v-if="loading" class="loading-content">
            <el-icon class="loading-icon" :color="color" :size="size">
                <Loading />
            </el-icon>
            <span class="loading-text">{{ text || '正在加载中...' }}</span>
        </div>
        <div v-else class="no-more">
            {{ noMoreText || '暂无更多数据' }}
        </div>
    </div>
</template>

<script setup>
import { Loading } from '@element-plus/icons-vue'
import { ref, defineProps, defineEmits, onMounted, onUnmounted } from 'vue'

const target = ref(null)
let observer = null  // 在组件作用域声明观察器变量
let isLoading = false
const emit = defineEmits(['load-more'])
onMounted(() => {
    if (isLoading) return
    observer = new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting) {
            isLoading = true
            emit('load-more')
            isLoading = false
        }
    })
    observer.observe(target.value)
})

onUnmounted(() => {
    // 使用已定义的observer变量
    if (observer) {
        observer.disconnect()
    }
})
const props = defineProps({
    loading: {
        type: Boolean,
        default: true
    },
    hasMore: {
        type: Boolean,
        default: true
    },
    text: String,
    noMoreText: String,
    color: {
        type: String,
        default: '#409eff'
    },
    size: {
        type: [Number, String],
        default: 24
    }
})
</script>

<style lang="scss" scoped>
// 确保观察元素始终可见
.observer-target {
    min-height: 1px; // 保持元素可见性
    position: relative;
    text-align: center;
    padding: 20px 0;
    margin: 16px 0;
    transition: all 0.3s ease;

    .loading-content {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;

        .loading-icon {
            animation: rotating 1.5s linear infinite;
        }

        .loading-text {
            color: inherit;
            font-size: 14px;
        }
    }
}

@keyframes rotating {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}
</style>